package com.auto.learning.activity;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.auto.learning.R;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.bean.UserInfoBean;
import com.auto.learning.event.BindSuccessEvent;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.Handle;
import com.auto.learning.event.listener.DialogListener;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.service.MyUserInfo;
import com.auto.learning.tools.CheckUpdateThread;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.DateUtil;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.CircleImageView;
import com.auto.learning.view.CommonAlertDialog;
import com.auto.learning.view.SharedPreferencesUtils;
import com.auto.learning.view.SwitchButton;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zbar.lib.CaptureActivity;

public class MyBaseInfo extends BaseActivity implements OnCheckedChangeListener {
	
	private SwitchButton button_play_cont,button_download;
	private CircleImageView image_head;
	private TextView tv_loginname,tv_grade,tv_money;
	private DisplayImageOptions options;
	private RelativeLayout rel_login_name,rel_mygrade,rel_head,rel_about,rel_sleepmode,rel_loginout,rel_check_version,rel_bind,rel_capter,rel_mymoney;
	private boolean needRefresh = false;
	private LinearLayout lin_vip;
	private TextView tv_date;
	private Handle handle = new Handle(this){
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case HttpRequestHelper.GETDATA_SUCCESS:
				ResponeResult result = (ResponeResult) msg.obj;
				try {
					JSONObject jsonObject = new JSONObject(result.getData());
					int userId = jsonObject.getInt(HttpRequestHelper.USERID);
					SharedPreferencesUtils.setParam(MyBaseInfo.this, HttpRequestHelper.USERID, userId);
					UserInfoBean userInfoBean = new UserInfoBean();
					userInfoBean.setUserId(userId);
					MyUserInfo.getInstance().setUserInfoBean(userInfoBean);
					setResult(204);
					finish();
				} catch (JSONException e) {
					e.printStackTrace();
				}
				break;
			case 2:
				Log.d("handleMessagexxss", msg.arg1+"--"+msg.arg2 +"--"+ msg.obj);
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
//		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setViewInLine(R.layout.activity_mybase_info);
		initImageLoader();
		initView();
		TemporaryVariable.activities.push(this);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		TemporaryVariable.activities.removeElement(this);
		super.onDestroy();
	}
	
	/**
	 * @param date 2017-07-02
	 * @return
	 */
	private String parseData(String date){
		String result = "";
		if (!TextUtils.isEmpty(date)) {
			Date m_date = DateUtil.strConvertDate2(date);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy 年 M 月 d 日");
			result = sdf.format(m_date);
		}
		return result;
	}
	
	private String getPreviousYear(String date){
		String result = "";
		String[] temp = date.split("-");
		if (temp.length == 3) {
			try {
				int x = Integer.parseInt(temp[0]) - 1;
				result = x + "-" + temp[1] + "-" + temp[2];
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	
	private String formDate(String date){
		return parseData(getPreviousYear(date)) +"--" + parseData(date);
	}
	
	private void initView(){
		setTitle("个人信息");
		tv_date=(TextView) findViewById(R.id.tv_date);
		lin_vip=(LinearLayout) findViewById(R.id.lin_vip);
		button_play_cont = (SwitchButton) findViewById(R.id.button_play_cont);
		button_download = (SwitchButton) findViewById(R.id.button_download);
		button_play_cont.setChecked(!(boolean)SharedPreferencesUtils.getParam(this, HttpRequestHelper.CONTINUE_PLAY_BEFORE, true));
		button_download.setChecked(!(boolean)SharedPreferencesUtils.getParam(this, HttpRequestHelper.DWONLOAD_PLAY_CONTINUE, false));
		button_play_cont.setOnCheckedChangeListener(this);
		button_download.setOnCheckedChangeListener(this);
		rel_capter = (RelativeLayout) findViewById(R.id.rel_capter);
		rel_check_version = (RelativeLayout) findViewById(R.id.rel_check_version);
		rel_bind = (RelativeLayout) findViewById(R.id.rel_bind);
		rel_loginout = (RelativeLayout) findViewById(R.id.rel_loginout);
		rel_about = (RelativeLayout) findViewById(R.id.rel_about);
		rel_mygrade = (RelativeLayout) findViewById(R.id.rel_mygrade);
		rel_head = (RelativeLayout) findViewById(R.id.rel_head);
		rel_sleepmode = (RelativeLayout) findViewById(R.id.rel_sleepmode);
		image_head = (CircleImageView) findViewById(R.id.image_head);
		tv_loginname = (TextView) findViewById(R.id.tv_loginname);
		tv_grade = (TextView) findViewById(R.id.tv_grade);
		rel_login_name = (RelativeLayout) findViewById(R.id.rel_login_name);
		tv_money=(TextView) findViewById(R.id.tv_money);
		rel_mymoney=(RelativeLayout) findViewById(R.id.rel_mymoney);
		final UserInfoBean userInfoBean = MyUserInfo.getInstance().getUserInfoBean();
		if (userInfoBean != null) {
			ImageLoader.getInstance().displayImage(userInfoBean.getFaceUrl(), image_head, options);
			tv_loginname.setText(userInfoBean.getLoginName());
			tv_grade.setText(userInfoBean.getUserGrade());
			if(userInfoBean.getVipInfo()!=null){
				if (!TextUtils.isEmpty(userInfoBean.getVipInfo().getBalanceYuan())) {
					tv_money.setText(userInfoBean.getVipInfo().getBalanceYuan().replace("￥", "")+"元");
				}
				if(userInfoBean.getVipInfo().getVipType()==1){
					lin_vip.setVisibility(View.VISIBLE);
					tv_date.setText(formDate(userInfoBean.getVipInfo().getVipExpired())+"");
				}else{
					lin_vip.setVisibility(View.GONE);
				}
			}
		}else{
			lin_vip.setVisibility(View.GONE);
		}
		rel_mymoney.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent=new Intent(MyBaseInfo.this, MyMoneyActivity.class);
				startActivityForResult(intent, 233);
			}
		});
		rel_head.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MyBaseInfo.this, ChangeUserHead.class);
				startActivityForResult(intent, 100);
				overridePendingTransition(R.anim.changehead_in, 0);
			}
		});
		backBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (needRefresh) {
					setResult(205);
				}
				finish();
			}
		});
		rel_login_name.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MyBaseInfo.this, ChangeLoginNameActivity.class);
				startActivityForResult(intent, 100);
			}
		});
		rel_mygrade.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MyBaseInfo.this, MyGradeActivity.class);
				startActivity(intent);
			}
		});
		rel_about.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MyBaseInfo.this, AboutusActivity.class);
				startActivity(intent);
			}
		});
		rel_sleepmode.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent sleep_intent = new Intent(MyBaseInfo.this, MySleepModeActivity.class);
				startActivity(sleep_intent);
			}
		});
		rel_loginout.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final UserInfoBean userInfoBean = MyUserInfo.getInstance().getUserInfoBean();
				if (userInfoBean != null && !TextUtils.isEmpty(userInfoBean.getSessionId())) {
					CommonAlertDialog alertDialog = new CommonAlertDialog(MyBaseInfo.this);
					alertDialog.setTextMessage("确认退出当前账号吗？");
					alertDialog.setShowTitle(true);
					String[] a = {"确定","取消"};
					alertDialog.setBtns(new DialogListener() {

						@Override
						public void okButtonClick(Dialog dialog) {
							HttpRequestHelper.logout(MyBaseInfo.this, userInfoBean.getSessionId(), handle);
							dialog.dismiss();
						}

						@Override
						public void cancelButtonClick(Dialog dialog) {
							dialog.dismiss();
						}

						@Override
						public void otherButtonClick(Dialog dialog) {
							dialog.dismiss();
						}}, a);
					alertDialog.show();
				} else {
					CommonMethod.makeNotice(MyBaseInfo.this, "未登录");
				}
			}
		});
		rel_check_version.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				new CheckUpdateThread(MyBaseInfo.this,0).execute();
			}
		});
		rel_bind.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent bindIntent = new Intent(MyBaseInfo.this, BundingActivity.class);
				startActivityForResult(bindIntent,100);
			}
		});
		rel_capter.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MyBaseInfo.this, CaptureActivity.class);
				startActivity(intent);
			}
		});
		findViewById(R.id.include_layout).setVisibility(View.GONE);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 100 && resultCode == 201) {
			UserInfoBean userInfoBean = MyUserInfo.getInstance().getUserInfoBean();
			if (userInfoBean != null) {
				needRefresh = true;
				ImageLoader.getInstance().displayImage(userInfoBean.getFaceUrl(), image_head, options);
				tv_loginname.setText(userInfoBean.getLoginName());
			}
		}else if (requestCode == 100 && resultCode == 202){
			UserInfoBean userInfoBean = MyUserInfo.getInstance().getUserInfoBean();
			if (userInfoBean != null) {
				needRefresh = true;
				tv_loginname.setText(userInfoBean.getLoginName());
			}
		}else if (requestCode == 100 && (resultCode == 206 || resultCode == 207)) {
			EventBus.getEventBus("bind_success_refresh").post(new BindSuccessEvent(resultCode));
		}
		if (requestCode == 233) {  //充值成功后，刷新
			UserInfoBean userInfoBean = MyUserInfo.getInstance().getUserInfoBean();
			if (userInfoBean != null) {
				if(userInfoBean.getVipInfo() != null){
					if (!TextUtils.isEmpty(userInfoBean.getVipInfo().getBalanceYuan())) {
						tv_money.setText(userInfoBean.getVipInfo().getBalanceYuan().replace("￥", "")+"元");
					}
					if(userInfoBean.getVipInfo().getVipType() == 1){
						lin_vip.setVisibility(View.VISIBLE);
						tv_date.setText(formDate(userInfoBean.getVipInfo().getVipExpired())+"");
					}else{
						lin_vip.setVisibility(View.GONE);
					}
				}
			}else{
				lin_vip.setVisibility(View.GONE);
			}
		}
	}
	
	
	private void initImageLoader(){
		options = new DisplayImageOptions.Builder()
		.showImageOnLoading(R.drawable.me_user)
		.showImageForEmptyUri(R.drawable.me_user)
		.showImageOnFail(R.drawable.me_user).cacheInMemory(true)
		.cacheOnDisk(true).considerExifParams(true)
		.bitmapConfig(Bitmap.Config.RGB_565).build();
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		switch (buttonView.getId()) {
		case R.id.button_play_cont:
			SharedPreferencesUtils.setParam(this, HttpRequestHelper.CONTINUE_PLAY_BEFORE, !isChecked);
			break;
		case R.id.button_download:
			SharedPreferencesUtils.setParam(this, HttpRequestHelper.DWONLOAD_PLAY_CONTINUE, !isChecked);
			break;
		}
	}
}
